import 'braft-editor/dist/index.css';
import React from 'react';
import BraftEditor, { ControlType, MediaType } from 'braft-editor';

interface Iprops {
  values?: string;
  onChange?: any;
  onBlur?: any;
  onFocus?: any;
  onEnter?: any
  disabled: boolean;
}
interface Istate {
  editorState: BraftEditor
  outputHTML: string,
  outputText: string
}

interface cc {

  id: string,
  title: string,
  alt: string,
  loop: boolean, // 指定音视频是否循环播放
  autoPlay: boolean, // 指定音视频是否自动播放
  controls: boolean, // 指定音视频是否显示控制栏
  poster: string, // 指定视频播放器的封面
}

export default class BasicDemo extends React.Component<Iprops> {
  isLivinig!: boolean;

  state: Istate = {
    editorState: BraftEditor.createEditorState(''),
    outputHTML: '<p></p>',
    outputText: ''
  };

  componentDidMount() {
    this.isLivinig = true;
    setTimeout(this.setEditorContentAsync);
  }

  componentWillUnmount() {
    this.isLivinig = false;
  }

  handle = (e: KeyboardEvent) => {
    if (e.keyCode === 13) {
      e.preventDefault();
      this.props.onEnter(this.state.outputHTML, this.state.outputText)
      // this.setState((state: Istate) => {
      //   return {
      //     editorState: BraftEditor.createEditorState(''),
      //     outputHTML: '<p></p>',
      //     outputText: ''
      //   }
      // });
    }
  }

  handleChange = (editorState: any) => {
    this.setState((state: Istate) => {
      this.props.onChange(state.outputHTML, state.outputText);
      return {
        editorState: editorState,
        outputHTML: editorState.toHTML(),
        outputText: editorState.toText()
      }
    });
  };

  setEditorContentAsync = () => {
    this.isLivinig &&
      this.props?.values &&
      this.setState({
        editorState: BraftEditor.createEditorState(''),
      });
  };

  render() {
    const { editorState } = this.state;
    const controls = [
      'bold',
      'italic',
      'underline',
      'separator',
      'link',
      'media',
    ];
    const media: MediaType = {
      uploadFn(param) {
        const serverURL = '/upload'
        const xhr = new XMLHttpRequest
        const fd = new FormData()

        const successFn = (response: any) => {
          // 假设服务端直接返回文件上传后的地址
          // 上传成功后调用param.success并传入上传后的文件地址
          param.success({
            url: '/' + param.file.name,
            meta: {
              id: 'media',
              title: 'xxx',
              alt: 'xxx',
              loop: true, // 指定音视频是否循环播放
              autoPlay: true, // 指定音视频是否自动播放
              controls: true, // 指定音视频是否显示控制栏
              poster: 'http://xxx/xx.png', // 指定视频播放器的封面
            } as cc
          })
        }

        const progressFn = (event: any) => {
          // 上传进度发生变化时调用param.progress
          param.progress(event.loaded / event.total * 100)
        }

        const errorFn = (response: any) => {
          // 上传发生错误时调用param.error
          param.error({
            msg: 'unable to upload.'
          })
        }

        xhr.upload.addEventListener("progress", progressFn, false)
        xhr.addEventListener("load", successFn, false)
        xhr.addEventListener("error", errorFn, false)
        xhr.addEventListener("abort", errorFn, false)

        fd.append('file', param.file)
        xhr.open('POST', serverURL, true)
        xhr.send(fd)

      },
    }

    return (
      <div>
        <div className="editor-wrapper" style={{ border: 'none' }}>
          <BraftEditor
            readOnly={this.props.disabled}
            controls={controls as ControlType[]}
            contentStyle={{
              height: '200px',
              boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)',
            }}
            imageControls={[{
              render: (a) => {
                a.width = 200
              }
            }]}
            value={editorState}
            onChange={this.handleChange}
            onBlur={() => {
              window.onkeydown = null
            }}
            media={media}
            onFocus={() => {
              window.onkeydown = this.handle
            }}
          />
        </div>
      </div>
    );
  }
}
